//
//  UITextView+Emoticon.swift
//  01-表情
//
//  Created by mac on 15/10/27.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit

extension UITextView: UITextViewDelegate {
    var emoticontext: String {
        let attributeText = attributedText
        var strM = String()
        attributeText.enumerateAttributesInRange(NSRange(location: 0, length: attributeText.length), options: []) { (dict, range, _) -> Void in
            if let attachment = dict["NSAttachment"] as? HMEmotionAttachment {
                print("图片\(attachment.emoticon)")
                strM += attachment.emoticon.chs ?? ""
            } else {
                let str = (attributeText.string as NSString).substringWithRange(range)
                
                strM += str
            }
        }
        return strM

    }
    
    // MARK - 插入表情
    func insertEmotion(emoticon:HMEmoticon) {
        // 空白表情
        if emoticon.isBlank {
            return
        }
        // 删除按钮
        if emoticon.isRemoved {
            deleteBackward()
            return
        }
        // emoji
        if let emoji = emoticon.emoji {
            replaceRange(selectedTextRange!, withText: emoji)
            return
        }
        // 图片表情
        insertImageEmoticon(emoticon)
        // 发表情不会出发代理方法
        delegate?.textViewDidChange?(self)
        
    }
    // 插入图片表情
    private func insertImageEmoticon(emoticon: HMEmoticon) {
        // 1.图片的属性文本
        let attachment = HMEmotionAttachment(emoticon: emoticon)
        attachment.image = UIImage(contentsOfFile: emoticon.imagePath)
        // 字体的线高
        let lineHeight = font!.lineHeight
        attachment.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
        // 获得图片文本
        let imageText = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
        
        // 添加 ‘字体’
        imageText.addAttribute(NSFontAttributeName, value: font!, range: NSRange(location: 0, length: 1))
        // 2. 记录textView attribute -> 转换成可变的
        let strM = NSMutableAttributedString(attributedString: attributedText)
        // 3.插入图片文本
        strM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
        // 4. 替换属性文本
        // 记录光标的位置
        let range  = selectedRange
        attributedText = strM
        selectedRange = NSRange(location: range.location + 1, length: 0)
        
    }
}